﻿using System;
using System.Windows.Forms;

namespace Commonality.Model
{
    public partial class LogForm : Form
    {
        public delegate void PrintLoggerInfoCallBack(object Info, string InfoLevel);
        private const int SHOWLOGLINENUM = 500;
        public LogForm()
        {
            InitializeComponent();
            InitLog();
        }
        private void InitLog()
        {
            LogPrint.BoilerEventLog += new LogPrint.BoilerLogHandler(PrintLoggerInfo);            
        }
        /// <summary>
        /// 委托回调函数,显示日志
        /// </summary>
        /// <param name="Info">日志内容</param>
        /// <param name="InfoLevel">信息级别：3警告信息，黄色字体；4错误信息，红色字体</param>
        private void PrintLoggerInfo(object Info, string InfoLevel)
        {
            try
            {
                if (rtbInfo.InvokeRequired)
                {
                    PrintLoggerInfoCallBack d = new PrintLoggerInfoCallBack(PrintLoggerInfo);
                    this.Invoke(d, new object[] { Info, InfoLevel });
                }
                else
                {
                    // 将内容插入到第一行,索引0是 rtbInfo 第一行位置
                    string newLine = DateTime.Now.ToString("HH:mm:ss") + ": " + Info + InfoLevel + Environment.NewLine;
                    rtbInfo.Text = rtbInfo.Text.Insert(0, newLine);

                    if (this.rtbInfo.Lines.Length >= SHOWLOGLINENUM + 1)   //只显示最新500行数据
                    {
                        string[] lines = this.rtbInfo.Lines;
                        string[] newLines = new string[SHOWLOGLINENUM];
                        Array.Copy(lines, 0, newLines, 0, newLines.Length);
                        this.rtbInfo.Lines = newLines;
                    }
                    //在尾部追加
                    //rtbInfo.AppendText(DateTime.Now.ToString("HH:mm:ss") + ": " + Info);
                    //rtbInfo.AppendText(Environment.NewLine);
                    //自动显示首行
                    rtbInfo.ScrollBars = RichTextBoxScrollBars.Both;
                    rtbInfo.Select(0, 0);
                    rtbInfo.ScrollToCaret();
                }
            }
            catch (Exception)
            {

            }

        }
    }
}
